import { useEffect, useRef, useState } from 'react'

const usePagination = ({ api, params }: UsePaginationProps) => {
	const requestParamsRef = useRef<Record<string, any>>({})
	const paginationRef = useRef({ current: 1, pageSize: 20 })
	const [list, setList] = useState<any>([])
	const [loading, setLoading] = useState(false)
	const [isLastPage, setIsLastPage] = useState(false)
	const [error, setError] = useState(false)

	const run = async () => {
		try {
			const { records, pages } = await api(
				Object.assign(
					{},
					paginationRef.current,
					params,
					requestParamsRef.current
				)
			)

			setList(
				paginationRef.current.current === 1 ? records : list.concat(records)
			)

			paginationRef.current.current === Number.parseInt(pages) &&
				setIsLastPage(true)
		} catch (e) {
			setError(true)
		} finally {
			setLoading(false)
		}
	}

	useEffect(() => {
		loading && run()
	}, [loading])

	const reload = () => {
		setLoading(true)
	}
	const refresh = () => {
		paginationRef.current = { ...paginationRef.current, current: 1 }
		setLoading(true)
	}
	const fetchNextPage = () => {
		paginationRef.current = {
			...paginationRef.current,
			current: paginationRef.current.current + 1
		}
		setLoading(true)
	}

	const setRequestParams = params => {
		requestParamsRef.current = { ...requestParamsRef.current, ...params }
		paginationRef.current = { ...paginationRef.current, current: 1 }
	}

	return {
		list,
		requestParamsRef,
		setRequestParams,
		loading,
		setLoading,
		isLastPage,
		refresh,
		reload,
		error,
		fetchNextPage
	}
}

export default usePagination
